package faf.services;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * Il s'agit d'une classe qui permet l'envoi d'email
 */
public class MailService {
	
	String host;
	String port;
	String address;
	
	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getPort() {
		return port;
	}

	public void setPort(String port) {
		this.port = port;
	}
	
	public String getAddress() {
		return address;
	}

	/**
	 * Adresse du serveur smtp
	 * @param address
	 */
	public void setAddress(String address) {
		this.address = address;
	}

	
	public void sendMail(String email, String title, String body) throws Exception {
		Properties props = new Properties();
		props.put("mail.smtp.host", getHost());
		props.put("mail.smtp.port", getPort());

		Session mailSession = Session.getDefaultInstance(props);
		Message simpleMessage = new MimeMessage(mailSession);

		InternetAddress fromAddress = null;
		InternetAddress toAddress = null;
		try {
			fromAddress = new InternetAddress(
					address);
			toAddress = new InternetAddress(email);
		} catch (AddressException e) {
			e.printStackTrace();
			throw new Exception("Impossible d'envoyer le mail : adresse invalide");
		}

		try {
			simpleMessage.setFrom(fromAddress);
			simpleMessage.setRecipient(RecipientType.TO, toAddress);
			simpleMessage.setSubject(title);
			simpleMessage.setText(body);
			Transport.send(simpleMessage);
		} catch (MessagingException e) {
			e.printStackTrace();
			throw new Exception("Impossible d'envoyer le mail: configuration invalide du serveur de mail");
		}

	}
}
